// pages/mine/room_register/steps_one/steps_one.js
import Toast from '../../../../miniprogram_npm/@vant/weapp/toast/toast'
import Dialog from "../../../../miniprogram_npm/@vant/weapp/dialog/dialog"

const app = getApp()
const log = new app.appLogs()
const http = new app.appHttp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    numList: [{
      name: '实名登记'
    }, {
      name: '入住房间'
    }, {
      name: '物业审核'
    }, {
      name: '登记完成'
    }, ],
    num: 0,
    //拍摄身份证要求
    cardClaimList: [{
      url: '/common/image/card_bz.png',
      isOk: true,
      title: "标准"
    },{
      url: '/common/image/card_qs.png',
      title: "边框缺失"
    },{
      url: '/common/image/card_mh.png',
      title: "照片模糊"
    },{
      url: '/common/image/card_sg.png',
      title: "闪光强烈"
    }],
    //拍摄人脸要求
    peopleClaimList:[{
      url: '/common/image/people_bz.png',
      isOk: true,
      title: "标准"
    },{
      url: '/common/image/people_qs.png',
      title: "边框缺失"
    },{
      url: '/common/image/people_mh.png',
      title: "照片模糊"
    },{
      url: '/common/image/people_sg.png',
      title: "闪光强烈"
    }],

    //身份证照片地址
    cardImageUrl: null,
    //人脸照片地址
    peopleImageUrl: null,

    //证件验证弹窗
    show: false,
    //证件类型
    typeShow: false,
    typeList: [],
    type: null,
    //证件号码
    credentialsNumber: null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //清空身份证照片地址
    app.globalData.cardImageUrl = null
    //清空人脸照片地址
    app.globalData.peopleImageUrl = null
    //先弹窗
    this.setData({
      show: true
    })
  },

  /**
   * 身份证拍照
   * @param e
   */
  onCameraCard: function(e){
    wx.getSetting({
      success(res) {
        log.e(JSON.stringify(res))
        if (!res.authSetting["scope.camera"]){
          log.e("没有权限")
          wx.authorize({
            scope: "scope.camera",
            success() {
              log.e("摄像头权限获取成功")
              wx.navigateTo({
                //身份证
                url: '../camera/card/card'
              })
            },
            fail() {
              Toast.fail("您已拒绝拍照权限，请允许权限后重试")
            }
          })
        }else {
          log.e("有权限")
          wx.navigateTo({
            //身份证
            url: '../camera/card/card'
          })
        }
      },
      fail(res) {
        Toast.fail("相机权限获取失败，请稍后重试")
      }
    })
  },

  /**
   * 人脸拍照
   * @param e
   */
  onCameraPeople: function(e){
    if (this.data.cardImageUrl == null){
      Toast.fail('请先上传身份证照片')
      return
    }
    wx.getSetting({
      success(res) {
        log.e(JSON.stringify(res))
        if (!res.authSetting["scope.camera"]){
          log.e("没有权限")
          wx.authorize({
            scope: "scope.camera",
            success() {
              log.e("摄像头权限获取成功")
              wx.navigateTo({
                //人脸
                url: '../camera/people/people'
              })
            },
            fail() {
              Toast.fail("您已拒绝拍照权限，请允许权限后重试")
            }
          })
        }else {
          log.e("有权限")
          wx.navigateTo({
            //人脸
            url: '../camera/people/people'
          })
        }
      },
      fail(res) {
        Toast.fail("相机权限获取失败，请稍后重试")
      }
    })
  },

  /**
   * 下一步
   * @param e
   */
  onNextSteps: function(e){
    if (app.globalData.cardImageUrl == null){
      Toast.fail('请上传身份证照片')
      return
    }
    // if (app.globalData.peopleImageUrl == null){
    //   Toast.fail('请上传头像照片')
    //   return
    // }
    log.e(JSON.stringify(app.globalData.cardInfo))
    Toast.loading({
      duration:0,
      message: '加载中',
      forbidClick: true,
    });
    let sex = 0
    if (app.globalData.cardInfo.sex === "男") {
      sex = 1
    }else if (app.globalData.cardInfo.sex === "女") {
      sex = 2
    }else if (app.globalData.cardInfo.sex === "女改男") {
      sex = 3
    }else if (app.globalData.cardInfo.sex === "男改女") {
      sex = 4
    }else if (app.globalData.cardInfo.sex === "未明确的性别") {
      sex = 5
    }
    // const birthday = app.globalData.cardInfo.birth.replace(/\//g,"-")
    let birth = app.globalData.cardInfo.birth.split("/")
    if (parseInt(birth[1]) < 10) {
      birth[1] = "0" + birth[1]
    }
    if (parseInt(birth[2]) < 10) {
      birth[2] = "0" + birth[2]
    }
    const birthday = birth[0] + '-' + birth[1] + '-' + birth[2]
    http.postHeader('people_info/register',{
      'Authorization': app.globalData.accessToken
    },{
      name: app.globalData.cardInfo.name,
      sex: sex,
      nation: app.globalData.cardInfo.nation + "族",
      birthday: birthday,
      hometown: app.globalData.cardInfo.address,
      identity_type: "D0005_1",
      identity_num: app.globalData.cardInfo.id,
      head_img_url: app.globalData.peopleImageUrl,
      face_img_url: app.globalData.peopleImageUrl,
      identity_img_url: app.globalData.cardImageUrl,
      source: "D0007_3"
    }).then(res => {
      if (res.data.code === http.REQUEST_OK){
        Toast.success('登记成功')
        setTimeout((res)=>{
          //刷新用户数据
          app.getUserInfo(res => {
            //查询该用户是否有入住房间
            http.get('room/addresses/people_id',{
              people_id: res.data.data.user.people_id
            }).then(res => {
              Toast.clear()
              if (res.data.code === http.REQUEST_OK) {
                if (res.data.data.length > 0) {
                  wx.navigateTo({
                    url: '../bound_room/bound_room'
                  })
                }else {
                  wx.redirectTo({
                    url: '../steps_two/steps_two'
                  })
                  // wx.navigateTo({
                  //   url: '../steps_two/steps_two'
                  // })
                }
              }else {
                wx.navigateTo({
                  // url: '../steps_two/steps_two'
                  url: '../bound_room/bound_room'
                })
              }
            },err => {
              Toast.fail('网络异常')
            })
          })
        },2000)
      }else {
        Toast.fail('登记失败')
      }
    },err => {
      Toast.fail('网络异常，登记失败')
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.data.cardImageUrl != null && this.data.peopleImageUrl != null) {
      this.onNextSteps()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 展示选择证件类型弹窗
   * @param e
   */
  onTypeShow: function (e) {
    if (this.data.typeList.length > 0) {
      this.setData({
        typeShow: true
      })
    } else {
      this.getCredentialsType()
    }
  },

  /**
   * 关闭选择证件类型弹窗
   * @param e
   */
  onTypeClose: function (e) {
    this.setData({
      typeShow: false
    })
  },

  /**
   * 证件类型选择
   * @param e
   */
  onTypeSelect: function (e) {
    this.setData({
      type: e.detail,
      typeShow: false
    })
  },

  /**
   * 获取证件类型
   */
  getCredentialsType: function () {
    Toast.loading({
      duration: 0,
      message: "加载中..."
    })
    http.get(app.globalData.xw_system_url + "dic/getDicListByName/open", {
      name: 'D0005'
    }).then(res => {
      Toast.clear()
      if (res.data.code === http.REQUEST_OK) {
        if (res.data.data.length > 0) {
          res.data.data.forEach(item => {
            item.name = item.dic_value
          })
          this.setData({
            typeList: res.data.data,
            typeShow: true
          })
        } else {
          Dialog.alert({
            title: "温馨提示",
            message: "未查询到相关证件类型，请联系管理员！"
          }).then(() => {  })
        }
      } else {
        Dialog.alert({
          title: "获取证件类型失败",
          message: res.data.msg
        }).then(() => {  })
      }
    }, err => {
      Toast.clear()
      Dialog.alert({
        title: "获取证件类型失败",
        message: "网络异常，请稍后再试！"
      }).then(() => {  })
    })
  },

  /**
   * 监听证件号码输入框
   * @param e
   */
  onInputCredentialsNumber: function (e) {
    this.setData({
      credentialsNumber: e.detail.value
    })
  },

  /**
   * 验证证件号码
   * @param e
   */
  onCredentialsVerify: function (e) {
    if (this.data.type == null) {
      Toast.fail("请选择证件类型")
      return false
    }
    if (this.data.credentialsNumber == null || this.data.credentialsNumber.length <= 0) {
      Toast.fail("请输入证件号码")
      return false
    }
    Toast.loading({
      duration: 0,
      message: "加载中..."
    })
    http.put(app.globalData.xw_api_url + "applet/user/bind/idCard",{
      applet_user_id: app.globalData.userInfo.applet_user_id,
      id_card: this.data.credentialsNumber,
      identity_type: this.data.type.flag
    }).then(res => {
      Toast.clear()
      if (res.data.code === http.REQUEST_OK) {
        if (res.data.data == null || res.data.data.length <= 0) {
          this.setData({
            show: false
          })
        } else {
          Toast.success("绑定成功")
          app.globalData.userInfo.people_id = res.data.data
          setTimeout(() => {
            wx.navigateBack()
          },1500)
        }
      } else {
        Dialog.alert({
          title: "提交失败",
          message: res.data.msg
        }).then(() => {  })
      }
    }, err => {
      Toast.clear()
      Dialog.alert({
        title: "提交失败",
        message: "网络异常，请稍后再试！"
      }).then(() => {  })
    })
  },
})